package com.thp.bigdata.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ServiceServerTask implements Runnable {

	Socket socket;
	
	InputStream in = null;
	OutputStream out = null;
	
	public ServiceServerTask(Socket socket) {
		this.socket = socket;
	}
	
	// 业务逻辑:跟客户端进行数据交互
	@Override
	public void run() {
		try {
			// 从socket连接中获取与client之间的网络输入输出流
			in = socket.getInputStream();
			out = socket.getOutputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			// 从网络通信输入流中获取客户端发送过来的数据
			// 注意:socketinputstream的读数据的方法是阻塞的
			String param = br.readLine();
			
			GetDataServiceImpl getDataServiceImpl = new GetDataServiceImpl();
			String result = getDataServiceImpl.getData(param);
			
			// 将调用结果写到socket的输出流中,以发送给客户端
			PrintWriter pw = new PrintWriter(out);
			pw.println(result);
			pw.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
